package com.ruoyi.common.utils.file;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

/**
 * Word文档处理工具类
 * 
 * @author ruoyi
 */
public class DocumentUtils
{
    private static final Logger log = LoggerFactory.getLogger(DocumentUtils.class);

    /**
     * 判断文件是否为Word格式
     * 
     * @param filePath 文件路径
     * @return true: Word文件, false: 非Word文件
     */
    public static boolean isWordDocument(String filePath)
    {
        if (filePath == null || filePath.isEmpty())
        {
            return false;
        }
        String lowerPath = filePath.toLowerCase();
        return lowerPath.endsWith(".doc") || lowerPath.endsWith(".docx");
    }

    /**
     * 读取Word文档中的所有文字内容
     * 
     * @param filePath 文件路径
     * @return 文档文字内容
     * @throws IOException 读取异常
     */
    public static String readWordContent(String filePath) throws IOException
    {
        File file = new File(filePath);
        if (!file.exists())
        {
            throw new IOException("文件不存在: " + filePath);
        }

        String content = "";
        String lowerPath = filePath.toLowerCase();

        if (lowerPath.endsWith(".docx"))
        {
            content = readDocx(filePath);
        }
        else if (lowerPath.endsWith(".doc"))
        {
            content = readDoc(filePath);
        }
        else
        {
            throw new IOException("不支持的文件格式，仅支持.doc和.docx格式");
        }

        return content;
    }

    /**
     * 读取.docx格式的Word文档
     * 
     * @param filePath 文件路径
     * @return 文档内容
     * @throws IOException 读取异常
     */
    private static String readDocx(String filePath) throws IOException
    {
        StringBuilder content = new StringBuilder();
        try (FileInputStream fis = new FileInputStream(filePath);
             XWPFDocument document = new XWPFDocument(fis))
        {
            List<XWPFParagraph> paragraphs = document.getParagraphs();
            for (XWPFParagraph paragraph : paragraphs)
            {
                String text = paragraph.getText();
                if (text != null && !text.trim().isEmpty())
                {
                    content.append(text).append("\n");
                }
            }
        }
        catch (Exception e)
        {
            log.error("读取.docx文件失败: {}", filePath, e);
            throw new IOException("读取.docx文件失败: " + e.getMessage(), e);
        }
        return content.toString().trim();
    }

    /**
     * 读取.doc格式的Word文档
     * 
     * @param filePath 文件路径
     * @return 文档内容
     * @throws IOException 读取异常
     */
    private static String readDoc(String filePath) throws IOException
    {
        String content = "";
        try (FileInputStream fis = new FileInputStream(filePath);
             HWPFDocument document = new HWPFDocument(fis);
             WordExtractor extractor = new WordExtractor(document))
        {
            content = extractor.getText();
        }
        catch (Exception e)
        {
            log.error("读取.doc文件失败: {}", filePath, e);
            throw new IOException("读取.doc文件失败: " + e.getMessage(), e);
        }
        return content.trim();
    }
}

